package validation

import (
	"context"
	"errors"
	"fmt"
	"github.com/go-redis/redis"
	"gorm.io/gen"
	"gorm.io/gorm"
	"mall_frontend_api/biz/consts"
	"mall_frontend_api/biz/dal"
	"mall_frontend_api/biz/dal/kv"
	"mall_frontend_api/biz/lib/biz_error"
	"mall_frontend_api/biz/model/user"
	"strings"
)

func CheckRegister(ctx context.Context, req *user.RegisterRequest) error {
	if req.Password != req.RePassword {
		return biz_error.NewBizError().SetLogMessage("密码确认不匹配").SetBadRequestErrorMessage("Confirm that the password is incorrect")
	}

	stringCmd := kv.GetRedisClient().Get(fmt.Sprintf(consts.RedisRegisterUserToken, req.Email))
	if errors.Is(stringCmd.Err(), redis.Nil) {
		return biz_error.NewBizError().SetLogMessage("redis失败 err %s", stringCmd.Err()).SetBadRequestErrorMessage("Verification code expired")
	}

	if stringCmd.Err() != nil {
		return biz_error.NewBizError().SetLogMessage("redis失败 err %s", stringCmd.Err()).SetServerErrorMessage("Internal server error, please try again")
	}

	if stringCmd.Val() != strings.ToUpper(req.Code) {
		return biz_error.NewBizError().SetLogMessage("验证码不匹配, redis %s, 收到 %d", stringCmd.Val(), strings.ToUpper(req.Code)).SetBadRequestErrorMessage("Verification code verification failed")
	}

	_, err := dao.UserDAO.GetByConditions(ctx, []gen.Condition{
		dal.User.Account.Eq(req.Email),
	})
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return biz_error.NewBizError().SetLogMessage("查询账号是否注册过").SetServerErrorMessage(err.Error())
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return biz_error.NewBizError().SetLogMessage("查询账号是否注册过").SetBadRequestErrorMessage("Email has already been registered, please log in")
	}
	return nil
}
